package com.talkology.pilot.manager.service.impl;

import com.talkology.pilot.common.constant.SysConstants;
import com.talkology.pilot.common.util.DateTimeUtil;
import com.talkology.pilot.database.dao.TeacherInfoMapper;
import com.talkology.pilot.database.model.TeacherInfo;
import com.talkology.pilot.manager.service.IFileMgtService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;

@Service
public class FileMgtServiceImpl implements IFileMgtService {
    private static final Logger LOG = LoggerFactory.getLogger(FileMgtServiceImpl.class);
    @Autowired
    private TeacherInfoMapper teacherInfoMapper;

    @Override
    @Transactional
    public String updTeacherProfile(Long teacherIndex, MultipartFile newProfile) {
        String profilesPath = System.getProperty("os.name").toLowerCase().startsWith("win") ?
                SysConstants.WINDOWS_PROFILES_PATH : SysConstants.LINUX_PROFILES_PATH;
        if (!newProfile.isEmpty()) {
            if (!checkImageFileName(newProfile.getOriginalFilename())) {
                throw new RuntimeException("Please enter the correct format file.");
            }
            if (newProfile.getSize() > 10485760) {
                throw new RuntimeException("The file is too big, please select one in 10M.");
            }
            String newProfileName = profilesPath + DateTimeUtil.getTimeShortString(new Date()) + "_" + newProfile.getOriginalFilename();
            // 磁盘保存
            BufferedOutputStream out = null;
            try {
                File folder = new File(profilesPath);
                if (!folder.exists())
                    folder.mkdirs();
                out = new BufferedOutputStream(new FileOutputStream(newProfileName));
                // 写入新文件
                out.write(newProfile.getBytes());
                out.flush();
                out.close();
            } catch (Exception e) {
                LOG.error("{}", e);
            } finally {
                try {
                    if (out != null)
                        out.close();
                } catch (IOException e) {
                    LOG.error("{}", e);
                }
            }
            //更改库
            TeacherInfo teacherInfo = teacherInfoMapper.selectByPrimaryKey(teacherIndex);
            if (teacherInfo != null) {
                teacherInfo.setPicAddr(newProfileName);
                teacherInfoMapper.updateByPrimaryKey(teacherInfo);
            }
            return newProfileName;
        } else {
            throw new IllegalArgumentException("Profile is empty. ");
        }
    }

    private boolean checkImageFileName(String name) {
        for(String x : SysConstants.image_type){
            if (name.contains(x)) {
                return true;
            }
        }
        return false;
    }

}
